
$.extend($.fn, {
        ///<summary>
        /// apply a slider UI
        ///</summary>
        itreegrid: function(setting,pagerParams) {
        	var ps = $.extend({
        		 url: null,
                 datatype: "json",
                 height:460,
              // autoheight:true,
                 treeGrid: true,
                 treeGridModel: "adjacency",
                 toppager:false,// 在表头添加button

                 cloneToTop:false,//

                 autowidth: true,
          
                 rowNum: 10000,
                 
                 treeIcons: {leaf:'ui-icon-document-b'},
             
                 jsonReader: {
                     repeatitems: false,
                     root: "rows"
                 },
                 _scrollX:false
            }, setting);
        	
        	var p_params={edit:false,add:false,edittext:"修改",addtext:'新增',deltext:'删除',del:false,search:false,cloneToTop:false,refresh:true};
        	if(pagerParams){
        		var p_params=$.extend(p_params,pagerParams);
        		if(ps.cloneToTop){
            		p_params.cloneToTop=true;
        		}
            }
        	var	grid = jQuery(this);
            grid.jqGrid(ps);
         	grid.jqGrid('navGrid',ps.pager,p_params);
        	if(!ps._scrollX){
                grid.closest(".ui-jqgrid-bdiv").css({ 'overflow-y' : 'auto' ,'overflow-x' : 'hidden'}); 

        	}
        	if(ps.cloneToTop){
        		  // remove some double elements from one place which we not need double
        		
                var topPagerDiv = $('#' + grid[0].id + '_toppager')[0];         // "#list_toppager"
                if(p_params.edit)
                $("#edit_" + grid[0].id + "_top", topPagerDiv).remove();        // "#edit_list_top"
                if(p_params.del)
                $("#del_" + grid[0].id + "_top", topPagerDiv).remove();         // "#del_list_top"

               // $("#search_" + grid[0].id + "_top", topPagerDiv).remove();      // "#search_list_top"
                if(p_params.refresh)
                $("#refresh_" + grid[0].id + "_top", topPagerDiv).remove();     // "#refresh_list_top"

                $("#" + grid[0].id + "_toppager_center", topPagerDiv).remove(); // "#list_toppager_center"

                $(".ui-paging-info", topPagerDiv).remove();



                var bottomPagerDiv = $("div#pager")[0];
                if(p_params.add)	
                $("#add_" + grid[0].id, bottomPagerDiv).remove();               // "#add_list"

        	}
       
        	
        	return grid;
        },
        igrid: function(setting,pagerParams) {
        	var ps = $.extend({
        		 url: null,
                 datatype: "json",
                 height:460,
              // autoheight:true,
                 toppager:false,// 在表头添加button
                 cloneToTop:false,//
                 autowidth: true,
                 rowList :[20,50,100],
                 rowNum :20,
                 treeIcons: {leaf:'ui-icon-document-b'},
                 jsonReader: {
                     repeatitems: false,
                     root: "rows"
                 },
                 viewrecords:true,
                 _scrollX:false,
                 _getNowUrl:function(){
                	 return null;
                 }
            }, setting);
        	var p_params={edit:false,edittext:"修改",addtext:'新增',add:false,deltext:'删除',del:false,search:false,cloneToTop:false,refresh:true,refreshtext:'刷新'};
        	if(pagerParams){
        		var p_params=$.extend(p_params,pagerParams);
        		if(ps.cloneToTop){
            		p_params.cloneToTop=true;
        		}						
            }
        	
        	var	grid = jQuery(this);
            grid.jqGrid(ps);
        	grid.jqGrid('navGrid',ps.pager,p_params);

        	if(!ps._scrollX){
                grid.closest(".ui-jqgrid-bdiv").css({ 'overflow-y' : 'auto' ,'overflow-x' : 'auto'}); 

        	}
        	if(ps.cloneToTop){
      		  // remove some double elements from one place which we not need double
      		
              var topPagerDiv = $('#' + grid[0].id + '_toppager')[0];         // "#list_toppager"
              if(p_params.edit)
              $("#edit_" + grid[0].id + "_top", topPagerDiv).remove();        // "#edit_list_top"
              if(p_params.del)
              $("#del_" + grid[0].id + "_top", topPagerDiv).remove();         // "#del_list_top"

             // $("#search_" + grid[0].id + "_top", topPagerDiv).remove();      // "#search_list_top"
              if(p_params.refresh)
              $("#refresh_" + grid[0].id + "_top", topPagerDiv).remove();     // "#refresh_list_top"

              $("#" + grid[0].id + "_toppager_center", topPagerDiv).remove(); // "#list_toppager_center"
              $("#" + grid[0].id + "_toppager_right", topPagerDiv).remove(); // "#list_toppager_center"

              $(".ui-paging-info", topPagerDiv).remove();



              var bottomPagerDiv = $("div#pager")[0];
              if(p_params.add)	
              $("#add_" + grid[0].id, bottomPagerDiv).remove();               // "#add_list"

        	}
        	
        	return grid;
        },
        dialogSel:function(setting){
        	var p = $.extend({
        		mulitSel:false,
        		dialogTitle:"",
        		listTitle:"",
        		height:400,
        		width:500,
        		listHeight:240,
        		modal:true,
        		url:"",
        		colNames:[],
        		colModel:[],
        		ExpandColumn:""
        		
            }, setting);
        	
        	if($(this).val()){
        		p.has=$(this).val().split(",");
        	}else{
        		p.has=[];
        	}
        	// 机构选择框 table 必须有id 没id jquery 报错
        	var tid="t_"+parseInt(10000*Math.random());
        	var div=' <div  title="'+p.dialogTitle+'">'
					+'<div>'+"<table id='"+tid+"'></table>"+'</div>'
					+'</div>';
			div=$(div).appendTo("body");
			var dialog= div.dialog({
		        resizable: false,
		        height:p.height,
		        width:p.width,
		        modal: p.modal,
		        autoOpen:false,
		        buttons: {
		            "确认": function(){
		           				 p.rs=[];
		            			  for (i = 0; i < p.c; i += 1) {
                    				 var id_ = $(p.rows[i].cells[p.iCol]).closest('tr')[0].id;
                           			 var   isChecked =$(p.rows[i].cells[p.iCol]).find("input").is(':checked');
                                
                               		 if(isChecked){
                               		
                              			 var data=$("#"+tid).jqGrid('getRowData',id_);
                                			p.rs.push(data);
                                	}
                    			}
                    			p.completeCb(p.rs);
                    			$( div).dialog( "close" );
		            		},
		            "取消": function(){$( div).dialog( "close" );}
		        }
		    });
		 
		    p.rs=new Array();
		    var grid= $(div).find("table").itreegrid({
	        	url: p.url,
	        	  colNames: p.colNames,  // 各列表头
             	  colModel: p.colModel,
	       		 width:"auto",
	       		 height:p.listHeight,
	           //  caption: p.listTitle,  // 表格标题
	             ExpandColumn: p.ExpandColumn, // 树形 要显示 的那一栏 name ,colModel 中的
	              loadComplete: function () {
	              grid_this=this;
	              var i;
                     p.iCol = $.fn.getColumnIndexByName ($(this), 'selected'), p.rows = this.rows,  p.c = p.rows.length;
                    for (i = 0; i < p.c; i += 1) {
                    	var id_ = $(p.rows[i].cells[p.iCol]).closest('tr')[0].id;
                    	
                            if(p.has &&(jQuery.inArray(id_,p.has)>-1)){
                            	// 默认选中
                            	$(p.rows[i].cells[p.iCol]).find("input").attr("checked","true");
                            }
                            if(!p.mulitSel){
		                             $(p.rows[i].cells[p.iCol]).click(function (e) {
		
		                            var id = $(e.target).closest('tr')[0].id,
		
		                                isChecked = $(e.target).is(':checked');
		
		                            	if(isChecked){
		                            		// 其他都设置为不可选
		                            		for (j = 0; j < p.c; j += 1) {
		                            			$(p.rows[j].cells[p.iCol]).find("input").removeAttr("checked");
		                            		}
		                            		$(e.target).attr("checked",true);
		                            		
		                            	}else{
		                            		$(e.target).removeAttr("checked");
		                            	}
									
		                        });
                            
                            }
                    }
                }
	              
	             
	        },{
	        	
	        });
	 
		   
		    var orgDialog={dialog:dialog,grid:grid,open:function(){
		    	$( div).dialog( "open" );
		    }};
		    return orgDialog;
        },
        orgSel:function(setting){
        	var p = $.extend({
        		mulitSel:false,
        		dialogTitle:"选择机构",
        		listTitle:"机构列表",
        		height:400,
        		width:550,
        		listHeight:230,
        		modal:true,
        		url:"",
        		colNames:["id","机构名称","机构代码","选择"],  // 各列表头,
        		colModel:[  					   // 各列值定义							
	                 {name: "id",index:'id',width:1, hidden:true, key:true},
	                 {name: "orgName", width:300,jsonmap:"data.orgName", resizable: true},
	                  {name:'orgCode',jsonmap:"data.orgCode",width:150},
	                  {name:'selected', index:'selected', width: 60, align:'center',
                    	 formatter:'checkbox', editoptions:{value:'1:0'},
                    	 formatoptions:{disabled:false}}
	                  
             
            	 ],
        		ExpandColumn:"orgName"
        		
            }, setting);
        	
        	return $(this).dialogSel(p);
        	
        	
        },
        getColumnIndexByName:function(grid2, columnName) {
				
                    var cm = grid2.jqGrid('getGridParam', 'colModel'), i, l;
                    for (i = 0, l = cm.length; i < l; i += 1) {
                        if (cm[i].name === columnName) {
                            return i; // return the index
                        }
                    }
                    return -1;

                },
          orgSel2:function(setting){
        	var p = $.extend({
        		two_state:true,
        		dialogTitle:"选择机构",
        		height:400,
        		width:500,
        		listHeight:240,
        		modal:true
        		
            }, setting);
        	
        	if($(this).val()){
        		p.has=$(this).val().split(",");
        	}else{
        		p.has=[];
        	}
        	// 机构选择框 table 必须有id 没id jquery 报错
        	var tid="t_"+parseInt(10000*Math.random());
        	var div=' <div  title="'+p.dialogTitle+'">'
					+"<div  id='"+tid+"'></div>"
					+'</div>';
			div=$(div).appendTo("body");
			
			
			
			var dialog= div.dialog({
		        resizable: false,
		        height:p.height,
		        width:p.width,
		        modal: p.modal,
		        autoOpen:false,
		        buttons: {
		            "确认": function(){
		           				 p.rs=[];
		            			 // 填充rs
		            			 var checked = grid.jstree("get_checked",null,true) ;
									var ids=[];
									checked.each(function(i,n){
										ids.push({id:$(n).attr("id"),
												  orgName:$(n).attr("name"),
												  orgCode:$(n).attr("orgCode")	
												 });
									});
									p.rs=ids;
                    			p.completeCb(p.rs);
                    			$( div).dialog( "close" );
		            		},
		            "取消": function(){$( div).dialog( "close" );}
		        }
		    });
		
		    p.rs=new Array();
		    $.jstree._themes = p.themes;
		    var grid= $(div).find("#"+tid).jstree({ 
					"json_data" : {
						"ajax" : {
							"url" : p.url,
							"data" : function (n) { 
								return { id : n.attr ? n.attr("id") : -1 }; 
							}
						}
					},
					checkbox:{"two_state":p.two_state},
					"plugins" : [ "themes", "json_data" ,"checkbox" ]
				});
		    var orgDialog={dialog:dialog,grid:grid,open:function(){
		    	$( div).dialog( "open" );
		    }};
		   
		    return orgDialog;
        }
		
});

function registerSubmit(grid,id,bf,af){
	$( id )
            .button()
            .click(function( event ) {
            	if(bf){
					var rs=bf();
					if(!rs){
						return;
					}
				else{
					$("input[name=re]").val("a");
               $(grid).jqGrid('setGridParam',{datatype:'json',page:1});
                $(grid).trigger("reloadGrid");
                 event.preventDefault();
				return;
				}
				}
				$("input[name=re]").val("a");
              $(grid).jqGrid('setGridParam',{datatype:'json',page:1});
              $(grid).trigger("reloadGrid");
               event.preventDefault();
            });
     if(af)af();       
}
 function getRowData(id){
   		var selectedId = $("#"+id).jqGrid("getGridParam", "selrow");  
		var rowData = $("#"+id).jqGrid("getRowData", selectedId);
		return rowData;
   	}
     
function registerTopBtn(grid,c,f,i){
	$(grid).jqGrid('navButtonAdd', '#' + $(grid)[0].id + '_toppager_left', { // "#list_toppager_left"
            caption: c,
            buttonicon: i?i:'ui-icon-wrench',
            onClickButton: function() {
            	
            		f();
            	
            }
        });
}
function registerDelOper(grid,url,id){
				
	 			
       			$.ajax({ 
                    type:"post", 
                    url:url, 
                    dataType: "json", 
                    data:{delete_id:id},
                    success: function (data) { 
                    	if(data.success) {
                    		ialert("系统","删除成功");
                    	}
                    	else ialert("系统",data.msg);
                    	
                    	$(grid).trigger("reloadGrid");
                    }, 
                    error: function(XMLHttpRequest, textStatus, errorThrown) {
                        //alert(XMLHttpRequest.status);
                        //alert(XMLHttpRequest.readyState);
                        //alert(textStatus);
                    	alert("发生错误！");
                    }
            	});
}

function buildRowOper(id,f,classx,title){
	 var   x = ("<span style='cursor:pointer' onclick='"+f+"(\"" + id + "\");' class='ui-icon "+classx+"'>"+title+"</span>");  
	
	return x;
}
function buildRowUpdate(id,f,t){
	return buildRowOper(id,f,"ui-icon-pencil",t?t:"修改");
}
function buildRowDel(id,f,t){
	return buildRowOper(id,f,"ui-icon-trash",t?t:"删除");
}